﻿using System;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Data.Linq.SqlClient;
using System.Data.Entity;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Routing;
using EKAABSInformationManagement.Service;
using EKAABSInformationManagement.Models;
using EKAABSInformationManagement.Database;

namespace EKAABSInformationManagement.Controllers
{
    public class MemberController : Controller
    {
        //
        // GET: /Member/
        public employeeService myEmpService { get; private set; }
        public IFormsAuthenticationService FormsService { get; private set; }
        public IMembershipService MembershipService { get; private set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (System.Web.HttpContext.Current.User.IsInRole("admin") != true)
            {
                HttpException ex = new HttpException(401, "");
                requestContext.HttpContext.AddError(ex);
            }
            if (myEmpService == null) myEmpService = new employeeService();
            if (FormsService == null) FormsService = new FormsAuthenticationService();
            if (MembershipService == null) MembershipService = new AccountMembershipService();
            base.Initialize(requestContext);
        }
        public ActionResult Index()
        {
            List<customerInfo> cInfo = myEmpService.getCustomerInfo();
            return View(cInfo);
        }

        [HttpPost]
        public ActionResult submit(customerInfo model)
        {
            try
            {
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, "111111", model.Email, model.Role);
                if (createStatus == MembershipCreateStatus.DuplicateUserName || createStatus == MembershipCreateStatus.DuplicateEmail)
                {
                    return Json(new { status = 1 });
                }
                else if (createStatus == MembershipCreateStatus.Success)
                {
                    myEmpService.insertIntoEmployees(model.UserName, model.Team, model.Position, model.startDate);
                    return Json(new { status = 2 });
                }
                else
                {
                    return Json(new { status = 4 });
                }

            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpPost]
        public ActionResult update(RegisterModel model)
        {
            try
            {
                if (Membership.GetUserNameByEmail(model.Email) == null) MembershipService.ChangeEmail(model.UserName, model.Email);
                MembershipService.ChangeRole(model.UserName, model.Role);
                MembershipService.ChangeTeamAndPosition(model.UserName, model.Team, model.Position);
                MembershipService.ChangeEmail(model.UserName, model.Email);
                return Json(new { status = 2 });
            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpPost]
        public ActionResult delete(string ids)
        {
            try
            {
                string[] strs = ids.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                MembershipService.deleteUserByIDs(strs);
                return Json(new { status = 2 });
            }
            catch
            {
                return Json(new { status = 4 });
            }
        }
        [HttpGet]
        public ActionResult getAllTeamAndPositonAndRoles()
        {
            try
            {
                List<team> tList = myEmpService.getAllTeam();
                List<position> posList = myEmpService.getAllPosition();
                string[] roles = Roles.GetAllRoles();
                StringBuilder result = new StringBuilder();
                result.Append("{\"team\":[");
                foreach (team t in tList)
                {
                    result.Append("{");
                    result.AppendFormat("\"ID\":\"{0}\", \"teamAlias\":\"{1}\"", t.ID, t.teamAlias);
                    result.Append("},");
                }
                if (tList.Count > 0) result.Remove(result.Length - 1, 1);
                result.Append("],\"position\":[");
                foreach (position t in posList)
                {
                    result.Append("{");
                    result.AppendFormat("\"ID\":\"{0}\", \"positionAlias\":\"{1}\"", t.ID, t.positionAlias);
                    result.Append("},");
                }
                if (posList.Count > 0) result.Remove(result.Length - 1, 1);
                result.Append("],\"roles\":[");
                foreach (string s in roles)
                {
                    result.Append("{");
                    result.AppendFormat("\"Roles\":\"{0}\"", s);
                    result.Append("},");
                }
                if (roles.Length > 0) result.Remove(result.Length - 1, 1);
                result.Append("]}");
                return Content(result.ToString());
            }
            catch { return Content("error"); }
        }

        [HttpGet]
        public ActionResult getCustomerDetailInfo(string alias)
        {
            try
            {
                customerInfo baseInfo = myEmpService.getCustomerInfoByAlias(alias);
                if (baseInfo == null) return Content("{\"status\":\"1\"}");
                StringBuilder result = new StringBuilder();
                result.Append("{\"status\":\"2\",\"baseInfo\":{");
                result.AppendFormat("\"userName\":\"{0}\",\"email\":\"{1}\",\"role\":\"{2}\",\"team\":\"{3}\",\"position\":\"{4}\"", baseInfo.UserName, baseInfo.Email, baseInfo.Role, baseInfo.Team, baseInfo.Position);
                result.Append("}");
                //get assets and network info,then set json value
                AssetService ass_service = new AssetService();
                List<asset> assets = ass_service.getAssetByAlias(alias);
                NetworkService nw_service = null;
                List<network> networks = null;
                if (assets.Count > 0) result.Append(",\"assets\":[");
                foreach (asset a in assets)
                {
                    if (networks == null)
                    {
                        networks = new List<network>();
                        nw_service = new NetworkService();
                    }
                    network nw = nw_service.getNetworkByAssetID(a.assetID);
                    if (nw != null) networks.Add(nw);
                    string dateStr = string.Empty;
                    if (a.date.HasValue) dateStr = a.date.Value.ToShortDateString();
                    result.Append("{");
                    result.AppendFormat("\"assetID\":\"{0}\", \"model\":\"{1}\", \"type\":\"{2}\", \"Sn\":\"{3}\", \"description\":\"{4}\", \"date\":\"{5}\"", a.assetID, a.model, a.type, a.S_n, a.description, dateStr);
                    result.Append("},");

                }
                if (assets.Count > 0)
                {
                    result.Remove(result.Length - 1, 1);
                    result.Append("]");
                }
                //set network info into json
                if (networks != null)
                {
                    if (networks.Count > 0) result.Append(",\"networks\":[");
                    foreach (network n in networks)
                    {
                        string dateStr = string.Empty;
                        if (n.latestUpdateDate.HasValue) dateStr = n.latestUpdateDate.Value.ToShortDateString();
                        result.Append("{");
                        result.AppendFormat("\"MAC\":\"{0}\", \"assetID\":\"{1}\", \"status\":\"{2}\", \"date\":\"{3}\"", n.MAC, n.assetID, Enum.GetName(typeof(EKAABSInformationManagement.Service.status), n.status), dateStr);
                        result.Append("},");
                    }
                    if (networks.Count > 0)
                    {
                        result.Remove(result.Length - 1, 1);
                        result.Append("]");
                    }
                }
                //get bell account info and set json value
                BellAccount acc_service = new BellAccount();
                accountInBell accInfo = acc_service.getBellAccountByAlias(alias);
                if (accInfo != null)
                {
                    string dateStr = string.Empty;
                    if (accInfo.latestUpdateDate.HasValue) dateStr = accInfo.latestUpdateDate.Value.ToShortDateString();
                    result.Append(",\"account\":{");
                    result.AppendFormat("\"accountID\":\"{0}\", \"empNo\":\"{1}\", \"status\":\"{2}\", \"domain\":\"{3}\", \"date\":\"{4}\"", accInfo.accountID, accInfo.empNo, Enum.GetName(typeof(EKAABSInformationManagement.Service.status), accInfo.status), accInfo.domain, dateStr);
                    result.Append("}");
                }
                //get card info and set json value
                CardService card_service = new CardService();
                cardInBell cardInfo = card_service.getCardByAlias(alias);
                if (cardInfo != null)
                {
                    string dateStr = string.Empty;
                    if (cardInfo.latestUpdateDate.HasValue) dateStr = cardInfo.latestUpdateDate.Value.ToShortDateString();
                    result.Append(",\"card\":{");
                    result.AppendFormat("\"cardNo\":\"{0}\", \"status\":\"{1}\",\"date\":\"{2}\"", cardInfo.cardNo, Enum.GetName(typeof(EKAABSInformationManagement.Service.status), cardInfo.status), dateStr);
                    result.Append("}");
                }
                result.Append("}");
                return Content(result.ToString());
            }
            catch { return Content("error"); }
        }
    }
}
